package com.ruoyi.common.utils;
import com.ruoyi.common.enums.SexEnum;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import java.time.LocalDate;
import java.util.Calendar;
import java.util.Objects;


public class IdCardUtil {

    /**
     * 通过身份证号码获取出生日期、性别、年龄
     *
     * @param certificateNo 身份证号码
     */
    public static IdCardInfo getBirAgeSex(String certificateNo) {
        IdCardInfo idCardInfo = new IdCardInfo();
        String birthday = null;
        Integer age = null;
        Integer sexCode = null;

        int year = LocalDate.now().getYear();
        char[] number = certificateNo.toCharArray();
        boolean flag = true;
        if (number.length == 15) {
            for (char c : number) {
                if (!flag)
                    return idCardInfo;
                flag = Character.isDigit(c);
            }
        } else if (number.length == 18) {
            for (int x = 0; x < number.length - 1; x++) {
                if (!flag)
                    return idCardInfo;
                flag = Character.isDigit(number[x]);
            }
        }
        if (flag && certificateNo.length() == 15) {
            birthday = "19" + certificateNo.substring(6, 8) + "-" + certificateNo.substring(8, 10) + "-"
                + certificateNo.substring(10, 12);
            sexCode = Integer.parseInt(certificateNo.substring(certificateNo.length() - 3, 15))
                % 2 == 0 ? 0 : 1;
            age = (year - Integer.parseInt("19" + certificateNo.substring(6, 8)));
        } else if (flag && certificateNo.length() == 18) {
            birthday = certificateNo.substring(6, 10) + "-" + certificateNo.substring(10, 12) + "-"
                + certificateNo.substring(12, 14);
            sexCode = Integer.parseInt(certificateNo.substring(certificateNo.length() - 4, certificateNo.length() - 1))
                % 2 == 0 ? 0 : 1;
            age = (year - Integer.parseInt(certificateNo.substring(6, 10)));
        }

        idCardInfo.setAge(age);
        idCardInfo.setSex(Objects.isNull(sexCode) ? null : SexEnum.valueOfCode(sexCode));
        idCardInfo.setBirthday(StringUtils.isBlank(birthday) ? null : LocalDate.parse(birthday));
        return idCardInfo;
    }

    @Data
    public static class IdCardInfo {

        /**
         * 年龄
         */
        private Integer age;

        /**
         * 联系人性别 0- 女， 1 -男
         */
        private SexEnum sex;

        /**
         * 生日
         */
        private LocalDate birthday;
    }
}
